package com.tarena.lbs.content.controller;

import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.base.protocol.model.Result;
import com.tarena.lbs.base.protocol.pager.PageResult;
import com.tarena.lbs.content.pojo.param.ArticleActionParam;
import com.tarena.lbs.content.pojo.param.ArticleContentParam;
import com.tarena.lbs.content.pojo.query.ArticleQuery;
import com.tarena.lbs.content.pojo.vo.ArticleActionPageResultVO;
import com.tarena.lbs.content.pojo.vo.ArticleCategoryVO;
import com.tarena.lbs.content.pojo.vo.ArticleVO;
import com.tarena.lbs.content.service.ArticleService;
import com.tarena.lbs.content.service.CategoryService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 文章业务模块接口
 */
@Slf4j
@RestController
@Tag(name = "文章相关功能接口")
@RequestMapping("/admin/content/article")
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    @Autowired
    private CategoryService categoryService;

    @Operation(summary = "文章分页列表查询")
    @GetMapping("/list")
    public Result<PageResult<ArticleVO>> pageList(ArticleQuery articleQuery)
        throws BusinessException{
        log.info("文章分页查询，参数：{}", articleQuery);
        PageResult<ArticleVO> pageResult = articleService.pageList(articleQuery);
        return new Result<>(pageResult);
    }

    @Operation(summary = "推文创作页面文章列表查询")
    @GetMapping("/twitter/list")
    public Result<PageResult<ArticleVO>> twitterPageList(@Valid ArticleQuery articleQuery)
        throws BusinessException{
        log.info("开始处理推文创作页面文章列表查询，请求参数：{}", articleQuery);
        
        // 参数校验
        if (articleQuery.getPageNo() == null || articleQuery.getPageNo() <= 0) {
            throw new BusinessException("400", "页码参数无效");
        }
        if (articleQuery.getPageSize() == null || articleQuery.getPageSize() <= 0) {
            throw new BusinessException("400", "每页数量参数无效");
        }
        
        // 设置默认查询状态为禁用状态（状态3）
        if (articleQuery.getArticleStatus() == null || articleQuery.getArticleStatus().isEmpty()) {
            log.debug("未指定文章状态，将使用默认状态：禁用状态(3)");
            articleQuery.setArticleStatus(Arrays.asList(3));
        } else {
            log.debug("使用客户端指定的状态过滤：{}", articleQuery.getArticleStatus());
        }
        
        try {
            PageResult<ArticleVO> pageResult = articleService.twitterPageList(articleQuery);
            log.info("成功完成推文创作页面文章列表查询，返回 {} 条记录", 
                    pageResult.getTotal() != null ? pageResult.getTotal() : 0);
            return new Result<>(pageResult);
        } catch (Exception e) {
            log.error("推文创作页面文章列表查询发生异常：{}", e.getMessage(), e);
            throw new BusinessException("-1", "文章列表查询失败");
        }
    }


    @Operation(summary = "文章保存")
    @PostMapping("/insert")
    public Result<Void> addArticle(@Valid ArticleContentParam param)
        throws BusinessException{
        log.debug("文章保存，参数：{}", param);
        articleService.addArticle(param);
        return Result.success();
    }


    @Operation(summary = "文章标签集合")
    @GetMapping("/getArticleLabel")
    public Result<Set<String>> articleLabels(ArticleQuery articleQuery) throws BusinessException {
        Set<String> labels = articleService.getAllArticleLabels();
        return new Result<>(labels);
    }


    @Operation(summary = "文章详情")
    @GetMapping("/get")
    public Result<ArticleVO> articleDetail(@RequestParam Integer id)throws BusinessException{
        if (id == null) {
            throw new BusinessException("400", "文章ID不能为空");
        }
        
        // 调用服务层获取文章详情
        ArticleVO article = articleService.getArticleById(id);
        return new Result<>(article);
    }
    
    @Operation(summary = "编辑文章详情")
    @GetMapping("/edit")
    public Result<ArticleVO> editArticleDetail(@RequestParam Integer id) throws BusinessException {
        log.info("获取文章编辑详情，文章ID: {}", id);
        if (id == null) {
            throw new BusinessException("400", "文章ID不能为空");
        }
        
        try {
            // 调用服务层获取文章详情
            ArticleVO article = articleService.getArticleById(id);
            log.info("成功获取文章编辑详情，文章ID: {}", id);
            return new Result<>(article);
        } catch (Exception e) {
            log.error("获取文章编辑详情失败，文章ID: {}", id, e);
            throw new BusinessException("-1", "获取文章详情失败");
        }
    }

    @Operation(summary = "更新文章")
    @PostMapping("/update")
    public Result<Integer> updateArticle(@Valid ArticleContentParam param) 
            throws BusinessException {
        log.info("更新文章，参数：{}", param);
        try {
            // 调用服务层更新文章
            articleService.addArticle(param);
            
            // 确保返回文章ID
            if (param.getId() == null) {
                throw new BusinessException("500", "文章更新失败，无法获取文章ID");
            }
            
            log.info("文章更新成功，文章ID: {}", param.getId());
            return new Result<>(param.getId());
        } catch (Exception e) {
            log.error("更新文章失败：{}", e.getMessage(), e);
            throw new BusinessException("-1", "更新文章失败: " + e.getMessage());
        }
    }
    
    @Operation(summary = "保存草稿")
    @PostMapping("/saveDraft")
    public Result<Integer> saveArticleDraft(@Valid ArticleContentParam param) 
            throws BusinessException {
        log.info("保存文章草稿，参数：{}", param);
        try {
            // 设置文章状态为待发布状态(1)
            param.setArticleStatus(1);
            
            // 调用服务层保存文章
            articleService.addArticle(param);
            
            // 确保返回文章ID
            if (param.getId() == null) {
                throw new BusinessException("500", "保存草稿失败，无法获取文章ID");
            }
            
            log.info("文章草稿保存成功，文章ID: {}", param.getId());
            return new Result<>(param.getId());
        } catch (Exception e) {
            log.error("保存文章草稿失败：{}", e.getMessage(), e);
            throw new BusinessException("-1", "保存草稿失败: " + e.getMessage());
        }
    }
    
    @Operation(summary = "更新并上线文章")
    @PostMapping("/updateAndPublish")
    public Result<Integer> updateAndPublishArticle(@Valid ArticleContentParam param) 
            throws BusinessException {
        log.info("更新并上线文章，参数：{}", param);
        try {
            // 设置文章状态为已发布状态(2)
            param.setArticleStatus(2);
            
            // 调用服务层更新文章
            articleService.addArticle(param);
            
            // 确保返回文章ID
            if (param.getId() == null) {
                throw new BusinessException("500", "更新并上线文章失败，无法获取文章ID");
            }
            
            log.info("文章更新并上线成功，文章ID: {}", param.getId());
            return new Result<>(param.getId());
        } catch (Exception e) {
            log.error("更新并上线文章失败：{}", e.getMessage(), e);
            throw new BusinessException("-1", "更新并上线文章失败: " + e.getMessage());
        }
    }
    
    @Operation(summary = "用户行为记录")
    @PostMapping("/behavior")
    public Result<Void> articleBehavior(ArticleActionParam param)
        throws BusinessException{
        return Result.success();
    }


    @Operation(summary = "查询已经点赞 收藏 访问过的文章")
    @GetMapping("/getBehaviorList")
    public Result<ArticleActionPageResultVO> getBehaviorLists(ArticleQuery query)
        throws BusinessException{
        return null;
    }
    
    @Operation(summary = "启用文章")
    @PostMapping("/enable")
    public Result<Void> enableArticle(@RequestParam Integer id) throws BusinessException {
        log.info("启用文章，参数：{}", id);
        try {
            articleService.updateStatus(id, 1);
            return Result.success();
        } catch (IllegalArgumentException e) {
            log.error("启用文章失败，参数错误：{}", e.getMessage());
            throw new BusinessException("-1", e.getMessage());
        } catch (RuntimeException e) {
            log.error("启用文章失败：{}", e.getMessage());
            throw new BusinessException("-1", e.getMessage());
        }
    }
    
    @Operation(summary = "禁用文章")
    @PostMapping("/disable")
    public Result<Void> disableArticle(@RequestParam Integer id) throws BusinessException {
        log.info("禁用文章，参数：{}", id);
        try {
            articleService.updateStatus(id, 2);
            return Result.success();
        } catch (IllegalArgumentException e) {
            log.error("禁用文章失败，参数错误：{}", e.getMessage());
            throw new BusinessException("-1", e.getMessage());
        } catch (RuntimeException e) {
            log.error("禁用文章失败：{}", e.getMessage());
            throw new BusinessException("-1", e.getMessage());
        }
    }
    
    @Operation(summary = "文章上线")
    @RequestMapping(value = "/publish", method = {RequestMethod.GET, RequestMethod.POST})
    public Result<Void> publishArticle(@RequestParam Integer id) throws BusinessException {
        log.info("文章上线，参数：{}", id);
        try {
            articleService.updateStatus(id, 2);  // 状态2表示已发布（上线）
            return Result.success();
        } catch (IllegalArgumentException e) {
            log.error("文章上线失败，参数错误：{}", e.getMessage());
            throw new BusinessException("-1", e.getMessage());
        } catch (RuntimeException e) {
            log.error("文章上线失败：{}", e.getMessage());
            throw new BusinessException("-1", e.getMessage());
        }
    }
    
    @Operation(summary = "文章下线")
    @RequestMapping(value = "/unpublish", method = {RequestMethod.GET, RequestMethod.POST})
    public Result<Void> unpublishArticle(@RequestParam Integer id) throws BusinessException {
        log.info("文章下线，参数：{}", id);
        try {
            articleService.updateStatus(id, 3);  // 状态3表示下线
            return Result.success();
        } catch (IllegalArgumentException e) {
            log.error("文章下线失败，参数错误：{}", e.getMessage());
            throw new BusinessException("-1", e.getMessage());
        } catch (RuntimeException e) {
            log.error("文章下线失败：{}", e.getMessage());
            throw new BusinessException("-1", e.getMessage());
        }
    }
    
    @Operation(summary = "设置文章为待发布状态")
    @PostMapping("/setPending")
    public Result<Void> setPending(@RequestParam Integer id) throws BusinessException {
        log.info("设置文章为待发布状态，参数：{}", id);
        try {
            articleService.updateStatus(id, 1);  // 状态1表示待发布
            return Result.success();
        } catch (IllegalArgumentException e) {
            log.error("设置文章为待发布状态失败，参数错误：{}", e.getMessage());
            throw new BusinessException("-1", e.getMessage());
        } catch (RuntimeException e) {
            log.error("设置文章为待发布状态失败：{}", e.getMessage());
            throw new BusinessException("-1", e.getMessage());
        }
    }
    
    @Operation(summary = "删除文章")
    @PostMapping("/delete")
    public Result<Void> deleteArticle(@RequestParam Integer id) throws BusinessException {
        log.info("删除文章，参数：{}", id);
        try {
            articleService.deleteArticle(id);
            return Result.success();
        } catch (IllegalArgumentException e) {
            log.error("删除文章失败，参数错误：{}", e.getMessage());
            throw new BusinessException("-1", e.getMessage());
        } catch (RuntimeException e) {
            log.error("删除文章失败：{}", e.getMessage());
            throw new BusinessException("-1", e.getMessage());
        }
    }
    
    @Operation(summary = "推文创作上线")
    @PostMapping("/twitter/publish")
    public Result<Void> twitterPublish(@RequestParam(required = false) Integer id,
                                     @RequestBody(required = false) Map<String, Object> requestBody) throws BusinessException {
        log.info("推文创作上线，参数：id={}, requestBody={}", id, requestBody);
        try {
            // 检查参数 - 支持RequestParam和RequestBody两种方式
            Integer articleId = id;
            if (articleId == null && requestBody != null && requestBody.containsKey("id")) {
                Object idObj = requestBody.get("id");
                if (idObj instanceof Integer) {
                    articleId = (Integer) idObj;
                } else if (idObj instanceof Number) {
                    articleId = ((Number) idObj).intValue();
                } else if (idObj instanceof String) {
                    try {
                        articleId = Integer.parseInt((String) idObj);
                    } catch (NumberFormatException e) {
                        throw new BusinessException("400", "文章ID格式不正确");
                    }
                }
            }

            if (articleId == null) {
                throw new BusinessException("400", "文章ID不能为空");
            }

            // 将文章状态从禁用(3)改为上线(2)
            articleService.updateStatus(articleId, 2);
            return Result.success();
        } catch (IllegalArgumentException e) {
            log.error("推文创作上线失败，参数错误：{}", e.getMessage());
            throw new BusinessException("-1", e.getMessage());
        } catch (RuntimeException e) {
            log.error("推文创作上线失败：{}", e.getMessage());
            throw new BusinessException("-1", e.getMessage());
        }
    }
    
    @Operation(summary = "新增/编辑推文")
    @PostMapping("/twitter/insert")
    public Result<Integer> createTwitter(@Valid ArticleContentParam param, 
                                       @RequestParam(required = false, defaultValue = "false") Boolean publish)
            throws BusinessException {
        log.info("新增/编辑推文，参数：{}, 是否直接上线: {}", param, publish);
        try {
            // 根据publish参数的值决定文章状态
            if (Boolean.TRUE.equals(publish)) {
                // 如果需要直接上线，设置状态为上线状态(2)
                param.setArticleStatus(2);
                log.info("设置文章状态为上线状态(2)");
            } else {
                // 否则设置为禁用状态(3)，等待后续上线操作
                param.setArticleStatus(3);
                log.info("设置文章状态为禁用状态(3)");
            }
            
            // 调用服务层保存文章
            articleService.addArticle(param);
            
            // 确保返回文章ID，便于前端处理后续操作
            if (param.getId() == null) {
                throw new BusinessException("500", "文章保存失败，无法获取文章ID");
            }
            
            log.info("文章保存成功，文章ID: {}, 最终状态: {}", param.getId(), param.getArticleStatus());
            return new Result<>(param.getId());
        } catch (Exception e) {
            log.error("新增/编辑推文失败：{}", e.getMessage(), e);
            throw new BusinessException("-1", "保存推文失败");
        }
    }

    @Operation(summary = "保存推文草稿")
    @PostMapping("/twitter/saveDraft")
    public Result<Integer> saveTwitterDraft(@Valid ArticleContentParam param)
            throws BusinessException {
        log.info("保存推文草稿，参数：{}", param);
        try {
            // 设置文章状态为待发布状态（1）
            param.setArticleStatus(1);
            // 调用服务层保存文章
            articleService.addArticle(param);
            
            // 返回文章ID，便于前端后续操作
            return new Result<>(param.getId());
        } catch (Exception e) {
            log.error("保存推文草稿失败：{}", e.getMessage(), e);
            throw new BusinessException("-1", "保存草稿失败");
        }
    }

    @Operation(summary = "获取所有启用的文章分类")
    @GetMapping("/getArticleCategory")
    public Result<List<ArticleCategoryVO>> articleCategories() throws BusinessException {
        List<ArticleCategoryVO> categories = categoryService.getAllEnabledCategories();
        return new Result<>(categories);
    }
}